﻿Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel

Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Data.SqlClient
Imports System.Management
Imports System.Xml
Imports System.Text
Imports System.IO

Imports Microsoft.ConfigurationManagement
Imports System.Management.ManagementScope

Imports Microsoft.ConfigurationManagement.ManagementProvider
Imports Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine



' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
' <System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Name:="PreStagedComputers", Namespace:="http://HEMSELL/PreStagedComputers/", Description:="Handles Prestaging Computers in MDT DB")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class Service1
    Inherits System.Web.Services.WebService
    Private _MDTConnStr As String = ""
    Private _MDTPWConnStr As String = ""
    Private _SCCMConnStr As String = ""
    Private _SCCMPWDConnStr As String = ""

    Public Sub New()
        ' Get Connection String from web.config
        Me._MDTConnStr = ConfigurationManager.ConnectionStrings("MDTDB").ConnectionString
        Me._MDTPWConnStr = ConfigurationManager.ConnectionStrings("MDTDBPWD").ConnectionString
        Me._SCCMConnStr = ConfigurationManager.ConnectionStrings("SCCMDB").ConnectionString
        Me._SCCMPWDConnStr = ConfigurationManager.ConnectionStrings("SCCMDBPWD").ConnectionString

    End Sub

    'Expose this as a web service
    <WebMethod()> _
    Public Function JarmaDarakowikj() As System.Xml.XmlDocument

        Dim dtResult As New DataTable("RESULTS")
        Dim colCollectionID As New DataColumn("TSCOLLECTIONID")
        Dim CollectionNAME As New DataColumn("TSCOLLECTIONNAME")
        Dim CollectionCOMMENT As New DataColumn("TSCOLLECTIONCOMMENT")
        dtResult.Columns.Add(colCollectionID)
        dtResult.Columns.Add(CollectionNAME)
        dtResult.Columns.Add(CollectionCOMMENT)

        Dim strSQL As String = ""
        strSQL = "Select CollectionID,Name,Comment From v_Collection "
        strSQL = strSQL & "Where CollectionID IN(Select CollectionID From v_Advertisement "
        strSQL = strSQL & " Where v_Advertisement.PackageID IN(Select PackageID  From v_TaskSequencePackage Where TS_Type = 2) )"

        Dim da As New SqlDataAdapter(strSQL, Me._SCCMPWDConnStr)

        'Create a data table to hold the results of the SQL
        Dim dt As New DataTable

        'Execute our SQL and fill our new DataTable
        da.Fill(dt)

        Dim resultRow As DataRow

        If dt.Rows.Count > 0 Then
            For Each row As DataRow In dt.Rows
                resultRow = dtResult.NewRow
                resultRow("TSCOLLECTIONID") = row("CollectionID")
                resultRow("TSCOLLECTIONNAME") = row("Name")
                resultRow("TSCOLLECTIONCOMMENT") = row("Comment")
                dtResult.Rows.Add(resultRow)
            Next
        Else
            resultRow = dtResult.NewRow
            resultRow("TSCOLLECTIONID") = "NO_COLLECTIONS_FOUND"
            dtResult.Rows.Add(resultRow)
        End If

        Dim dsResult As New DataSet("dsPreStaged")

        dsResult.Tables.Add(dtResult)
        Dim result As New XmlDataDocument(dsResult)

        Return result

    End Function



    'Expose this as a web service
    <WebMethod()> _
    Public Function CreateResourceRecord(ByVal MACAddress As String, ByVal UUID As String, ByVal ComputerName As String) As System.Xml.XmlDocument

        'Create a place to put the data and something to return to the client
        Dim dtResult As New DataTable("COMPUTERINFO")
        Dim colMAC As New DataColumn("MAC")
        Dim colUUID As New DataColumn("UUID")
        Dim colNAME As New DataColumn("NAME")
        Dim colResourceID As New DataColumn("ResourceID")
        dtResult.Columns.Add(colMAC)
        dtResult.Columns.Add(colUUID)
        dtResult.Columns.Add(colNAME)
        dtResult.Columns.Add(colResourceID)
        Dim resultRow As DataRow
        resultRow = dtResult.NewRow


        'Configuration Manager needs the MAC in the form of AA:AA:AA:AA:AA:AA
        '00:A0:C9:14:C8:29 = 17 Characters Long
        '00A0C914C829 = 12 character long



        Dim blnMACValid As Boolean ' Something to tell us if we found a matching string type
        If String.IsNullOrEmpty(MACAddress) = False Then
            MACAddress = MACAddress.ToUpper
            If Len(MACAddress) = 12 Then 'Then it is invalid or needs : Inserted
                blnMACValid = True
                Dim strTEMP As String = ""
                For i As Integer = 1 To 10 Step 2
                    strTEMP = strTEMP & Mid(MACAddress, i, 2) & ":"
                Next
                strTEMP = strTEMP & Right(MACAddress, 2)
                MACAddress = strTEMP
            End If
            ' Reformat macAddress to : separator.
            If Len(MACAddress) = 17 And blnMACValid = False Then
                blnMACValid = True
                Dim strToFind As String = Mid(MACAddress, 3, 1)
                MACAddress = MACAddress.Replace(strToFind, ":")
            End If
        End If
        If Len(MACAddress) = 17 Then
            blnMACValid = True
        Else
            blnMACValid = False
        End If

        Dim blnUUIDValid As Boolean = False

        If Len(UUID) = 32 Then
            blnUUIDValid = True
        End If



        Dim iResult As Integer = AddNewComputer(ComputerName, UUID, MACAddress, Connect)

        If blnMACValid = False Then
            MACAddress = ""
        End If

        If blnUUIDValid = False Then
            UUID = ""
        End If

        resultRow = dtResult.NewRow
        If String.IsNullOrEmpty(MACAddress) = True And String.IsNullOrEmpty(UUID) = True Then
            resultRow("MAC") = "MAC EMPTY"
            resultRow("UUID") = "UUID EMPTY"
            resultRow("NAME") = ComputerName

        Else
            resultRow("MAC") = MACAddress
            resultRow("UUID") = UUID
            resultRow("NAME") = ComputerName
        End If

        resultRow("ResourceID") = iResult
        dtResult.Rows.Add(resultRow)

        Dim dsResult As New DataSet("ADDCOMPUTER")

        dsResult.Tables.Add(dtResult)
        Dim result As New XmlDataDocument(dsResult)

        Return result



    End Function

    <WebMethod()> _
Public Function CreateAssociation(ByVal strSourceComputerName As String, ByVal strDestinationComputer As String) As System.Xml.XmlDocument

        Dim strSourceComputerResourceID As String = GetResourceID(Connect, strSourceComputerName)
        Dim strDestinationComputerResourceID As String = GetResourceID(Connect, strDestinationComputer)
        Dim strResult As String = "UNEXPECTED ERROR"
        Dim strTMP As String = "strSourceComputerResourceID=" & strSourceComputerResourceID & " AND strDestinationComputerResourceID=" & strDestinationComputerResourceID
        Try
            strResult = AssociateComputer(strSourceComputerResourceID, strDestinationComputerResourceID, Connect)
        Catch ex As Exception
            strResult = ex.Message & " Values Used (" & strTMP & ")"
        End Try

        Dim dtResult As New DataTable("ASSRESULT")
        Dim colResult As New DataColumn("ASSRESULT")
        dtResult.Columns.Add(colResult)

        Dim resultRow As DataRow

        resultRow = dtResult.NewRow
        resultRow("ASSRESULT") = strResult
        dtResult.Rows.Add(resultRow)

        Dim dsResult As New DataSet("dsPreStaged")

        dsResult.Tables.Add(dtResult)
        Dim result As New XmlDataDocument(dsResult)

        Return result

    End Function

    'Expose this as a web service
    <WebMethod()> _
    Public Function UpdateConfigurationWithMACUUID(ByVal MACAddress As String, ByVal UUID As String, ByVal IDENT As Integer) As System.Xml.XmlDataDocument

        'Build up the SQL and such to get the data
        Dim strSQL As String
        strSQL = "sp_UpdateConfigurationWithMACUUID '" & MACAddress & "','" & UUID & "','" & IDENT & "'"

        Dim da As New SqlDataAdapter(strSQL, Me._MDTPWConnStr)

        'da.SelectCommand.CommandType = CommandType.StoredProcedure
        'da.UpdateCommand.CommandType = CommandType.StoredProcedure

        'da.SelectCommand.Parameters.AddWithValue("@MACADDRESS", MACAddress)
        'da.SelectCommand.Parameters.AddWithValue("@UUID", UUID)
        'da.SelectCommand.Parameters.AddWithValue("@IDENT", IDENT)

        'Create a data table to hold the results of the SQL
        Dim dt As New DataTable

        'Execute our SQL and fill our new DataTable
        da.Fill(dt)

        Dim dtResult As New DataTable("RESULTS")
        Dim colResult As New DataColumn("UPDATECONFIGRESULT")
        dtResult.Columns.Add(colResult)

        Dim resultRow As DataRow

        For Each row As DataRow In dt.Rows
            resultRow = dtResult.NewRow
            resultRow("UPDATECONFIGRESULT") = row(0)
            dtResult.Rows.Add(resultRow)
        Next

        Dim dsResult As New DataSet("dsPreStaged")

        dsResult.Tables.Add(dtResult)
        Dim result As New XmlDataDocument(dsResult)

        Return result
        result.Save("MyConfigurations.xml")
    End Function

    'Expose this as a web service
    <WebMethod()> _
    Public Function GetConfigurations() As System.Xml.XmlDocument

        'Build up the SQL and such to get the data
        Dim strSQL As String
        strSQL = "sp_GetConfigurations"
        Dim da As New SqlDataAdapter(strSQL, Me._MDTPWConnStr)
        'Create a data table to hold the results of the SQL
        Dim dt As New DataTable
        'Execute our SQL and fill our new DataTable
        da.Fill(dt)

        'Create a place to put the data and something to return to the client
        Dim dtResult As New DataTable("ITEM")
        Dim colConfigID As New DataColumn("ConfigID")
        Dim colConfigDescription As New DataColumn("ConfigDescription")
        Dim colConfigComments As New DataColumn("ConfigComments")
        dtResult.Columns.Add(colConfigID)
        dtResult.Columns.Add(colConfigDescription)
        dtResult.Columns.Add(colConfigComments)
        Dim resultRow As DataRow
        resultRow = dtResult.NewRow

        For Each row As DataRow In dt.Rows
            resultRow = dtResult.NewRow
            resultRow("ConfigID") = row("ID")
            resultRow("ConfigDescription") = row("DESCRIPTION")
            resultRow("ConfigComments") = "NOT IMPLEMENTED YET"
            dtResult.Rows.Add(resultRow)
        Next


        Dim dsResult As New DataSet("CONFIGURATIONS")

        dsResult.Tables.Add(dtResult)
        Dim result As New XmlDataDocument(dsResult)

        Return result


    End Function

    'Expose this as a web service
    <WebMethod()> _
    Public Function GetComputerInformation(ByVal MACAddress As String, ByVal UUID As String) As System.Xml.XmlDocument

        'These Variables are what is returned to the caller
        Dim RESOURCEID As Integer = 0
        Dim NUMRESOURCERECORDS As Integer = 0
        Dim NUMTSS As Integer = 0
        Dim ADVERTISEMENTNAME As String = "NO TASK SEQUENCE ADS FOUND"
        Dim TSNAME As String = "NO TASK SEQUENCE ADS FOUND"
        Dim TSDESCRIPTION As String = "NO TASK SEQUENCE ADS FOUND"
        Dim TSCATEGORY As String = "NO TASK SEQUENCE ADS FOUND"

        'These variables are needed by the function
        Dim strSiteServer As String = ConfigurationManager.AppSettings("strSiteServer")
        Dim strSiteCode As String = ConfigurationManager.AppSettings("strSiteCode")
        Dim strUserName As String = ConfigurationManager.AppSettings("strUserName")
        Dim strPassword As String = ConfigurationManager.AppSettings("strPassword")
        Dim strCollIDS As String = ""
        Dim blnBailOut As Boolean = False
        Dim Scope As ManagementScope
        Dim oQuery As ManagementObjectSearcher
        Dim resultRow As DataRow
        Dim strHOSTNAME As String = System.Net.Dns.GetHostName().ToUpper()
        Dim strSCCMSERVER As String = strSiteServer.ToUpper()


        'Create a place to put the data and something to return to the client
        Dim dtResult As New DataTable("dtComputerInformation")
        Dim colOne As New DataColumn("RESOURCEID")
        Dim colTwo As New DataColumn("NUMRESOURCES")
        Dim colThree As New DataColumn("ADVERTISEMENTNAME")
        Dim colFour As New DataColumn("TSNAME")
        Dim colFive As New DataColumn("TSDESCRIPTION")
        Dim colSix As New DataColumn("TSCATEGORY")
        Dim colSeven As New DataColumn("NUMTSS")

        dtResult.Columns.Add(colOne)
        dtResult.Columns.Add(colTwo)
        dtResult.Columns.Add(colThree)
        dtResult.Columns.Add(colFour)
        dtResult.Columns.Add(colFive)
        dtResult.Columns.Add(colSix)
        dtResult.Columns.Add(colSeven)


        resultRow = dtResult.NewRow


        'GET THE RESOURCE ID = SEE IF MACHINE IS EVEN IN SCCM

        'Set the WQL we will issue to SCCM Server
        Dim queryString As String = "SELECT * FROM SMS_R_System WHERE MacAddresses = '" & MACAddress & "'"
        If UUID <> "" Then
            queryString &= " or SMBIOSGUID = '" & UUID & "'"
        End If






        If InStr(strSCCMSERVER, strHOSTNAME) Or InStr(strHOSTNAME, strSCCMSERVER) Then
            ' Connect to local computer.
            Scope = New ManagementScope("\\" & strSiteServer & "\root\SMS\SITE_" & strSiteCode)
            Scope.Options.Authentication = AuthenticationLevel.Default
            Scope.Options.Impersonation = ImpersonationLevel.Impersonate
            Scope.Connect()
        Else
            ' Connect to remote computer.
            Dim credentials As New ConnectionOptions
            credentials.Username = strUserName
            credentials.Password = strPassword
            Scope = New ManagementScope("\\" & strSiteServer & "\root\SMS\SITE_" & strSiteCode)
            Scope.Options = credentials
            Scope.Options.Authentication = AuthenticationLevel.Default
            Scope.Connect()
        End If


        oQuery = New ManagementObjectSearcher(queryString)

        oQuery.Scope = Scope
        For Each item As ManagementObject In oQuery.Get
            If item("RESOURCEID") > RESOURCEID Then 'This way we get the newest ResourceId for the machine
                RESOURCEID = item("RESOURCEID")
            End If
            NUMRESOURCERECORDS = NUMRESOURCERECORDS + 1
        Next


        'NOW WE KNOW IF THE MACHINE IS IN SCCM OR NOT

        If NUMRESOURCERECORDS = 1 Then 'Lets what collections it is in if we have a machine
            queryString = "SELECT CollectionID FROM SMS_FullCollectionMembership WHERE RESOURCEID = '" & RESOURCEID & "'"
            Dim oCollQuery As ManagementObjectSearcher = New ManagementObjectSearcher(queryString)
            oCollQuery.Scope = Scope


            For Each oColl As ManagementObject In oCollQuery.Get
                If strCollIDS = "" Then
                    strCollIDS = oColl("CollectionID").ToString()
                Else
                    strCollIDS = strCollIDS & ", " & oColl("CollectionID").ToString()
                End If
            Next
        End If

        If strCollIDS <> "" Then blnBailOut = False

        'NOW WE KNOW THE RESOURCEID AND THE COLLECTIONIDS OF THE COLLECTIONS IT IS IN

        If blnBailOut = False Then 'Lets see if those collections have any OS Deployment Task Sequnces Advertised to it
            'build the SQL
            Dim strSQL As String = ""
            strSQL = "Select ADVERTISEMENTNAME,	v_TaskSequencePackage.Name AS TSNAME,"
            strSQL = strSQL & "v_TaskSequencePackage.Description AS TSDESCRIPTION,v_TaskSequencePackage.Category AS TSCATEGORY "
            strSQL = strSQL & " From v_Advertisement Join v_TaskSequencePackage "
            strSQL = strSQL & " on v_Advertisement.PackageID = v_TaskSequencePackage.PackageID "
            strSQL = strSQL & " Where v_Advertisement.PackageID IN(Select PackageID From v_TaskSequencePackage Where TS_Type = 2) "
            strSQL = strSQL & " AND v_Advertisement.CollectionID IN('" & strCollIDS & "')"

            Dim da As New SqlDataAdapter(strSQL, Me._SCCMPWDConnStr)
            'Create a data table to hold the results of the SQL
            Dim dt As New DataTable

            'Execute our SQL and fill our new DataTable

            da.Fill(dt)

            'Now iterate through the data and add the values into our XML
            NUMTSS = dt.Rows.Count
            If NUMTSS > 0 Then 'we got some data back, process it
                Dim i As Integer = 0
                For Each row As DataRow In dt.Rows
                    If i = 0 Then
                        ADVERTISEMENTNAME = row("ADVERTISEMENTNAME")
                        TSNAME = row("TSNAME")
                        TSDESCRIPTION = row("TSDESCRIPTION")
                        TSCATEGORY = row("TSCATEGORY")
                    Else
                        ADVERTISEMENTNAME = ADVERTISEMENTNAME & "|" & row("ADVERTISEMENTNAME")
                        TSNAME = TSNAME & "|" & row("TSNAME")
                        TSDESCRIPTION = TSDESCRIPTION & "|" & row("TSDESCRIPTION")
                        TSCATEGORY = TSCATEGORY & "|" & row("TSCATEGORY")
                    End If
                    i = i + 1
                Next
            End If
        End If

        'Let's populate a data row
        resultRow = dtResult.NewRow
        resultRow("RESOURCEID") = RESOURCEID
        resultRow("NUMRESOURCES") = NUMRESOURCERECORDS
        resultRow("ADVERTISEMENTNAME") = ADVERTISEMENTNAME
        resultRow("TSNAME") = TSNAME
        resultRow("TSDESCRIPTION") = TSDESCRIPTION
        resultRow("TSCATEGORY") = TSCATEGORY
        resultRow("NUMTSS") = NUMTSS
        dtResult.Rows.Add(resultRow)

        'And send the data back to the client
        Dim dsResult As New DataSet("dsPreStaged")

        dsResult.Tables.Add(dtResult)
        Dim result As New XmlDataDocument(dsResult)
        Return result

    End Function

    'Expose this as a web service
    <WebMethod()> _
   Public Function CheckStaged(ByVal MACAddress As String, ByVal AssetTag As String, ByVal SerialNumber As String, ByVal UUID As String) As System.Xml.XmlDocument

        'Build up the SQL and such to get the data
        Dim strSQL As String
        strSQL = "sp_CheckPrestagedStatus"

        Dim da As New SqlDataAdapter(strSQL, Me._MDTPWConnStr)

        da.SelectCommand.CommandType = CommandType.StoredProcedure

        da.SelectCommand.Parameters.AddWithValue("@SerialNumber", SerialNumber)
        da.SelectCommand.Parameters.AddWithValue("@AssetTag", AssetTag)
        da.SelectCommand.Parameters.AddWithValue("@MacAddress", MACAddress)
        da.SelectCommand.Parameters.AddWithValue("@UUID", UUID)


        'Create a data table to hold the results of the SQL
        Dim dt As New DataTable

        'Execute our SQL and fill our new DataTable
        da.Fill(dt)

        'Create a place to put the data and something to return to the client
        Dim dtResult As New DataTable("dtPreStaged")
        Dim colOne As New DataColumn("PRESTAGED")
        Dim colTwo As New DataColumn("IDENT")
        Dim colThree As New DataColumn("AUTHORIZED")
        Dim colFour As New DataColumn("NUMROWS")
        Dim colFive As New DataColumn("DESCRIPTION")
        dtResult.Columns.Add(colOne)
        dtResult.Columns.Add(colTwo)
        dtResult.Columns.Add(colThree)
        dtResult.Columns.Add(colFour)
        dtResult.Columns.Add(colFive)

        Dim resultRow As DataRow
        resultRow = dtResult.NewRow
        Dim iRowsRet As Integer
        iRowsRet = dt.Rows.Count
        If dt.Rows.Count > 0 Then 'we got some data back, process it
            For Each row As DataRow In dt.Rows
                resultRow("IDENT") = row("ID")
                resultRow("AUTHORIZED") = row("OsInstall")
                resultRow("PRESTAGED") = "TRUE"
                resultRow("DESCRIPTION") = row("Description")
            Next
        Else
            resultRow("IDENT") = "0"
            resultRow("AUTHORIZED") = "FALSE"
            resultRow("PRESTAGED") = "FALSE"
            resultRow("DESCRIPTION") = "FALSE"
        End If
        resultRow("NUMROWS") = iRowsRet
        dtResult.Rows.Add(resultRow)

        Dim dsResult As New DataSet("dsPreStaged")

        dsResult.Tables.Add(dtResult)
        Dim result As New XmlDataDocument(dsResult)

        Return result

    End Function

    Private Function AddNewComputer(ByVal netBiosName As String, ByVal smBiosGuid As String, ByVal macAddress As String, ByVal connection As WqlConnectionManager) As Integer


        Try
            If smBiosGuid Is Nothing And macAddress Is Nothing Then
                Throw New ArgumentNullException("smBiosGuid or macAddress must be defined")
            End If

            ' Reformat macAddress to : separator.
            If String.IsNullOrEmpty(macAddress) = False Then
                macAddress = macAddress.Replace("-", ":")
            End If

            ' Create the computer.
            Dim inParams As Dictionary(Of String, Object) = New Dictionary(Of String, Object)
            inParams.Add("NetbiosName", netBiosName)
            inParams.Add("SMBIOSGUID", smBiosGuid)
            inParams.Add("MACAddress", macAddress)
            inParams.Add("OverwriteExistingRecord", False)

            Dim outParams As IResultObject = connection.ExecuteMethod("SMS_Site", "ImportMachineEntry", inParams)

            ' Add to All System collection.
            Dim collection As IResultObject = connection.GetInstance("SMS_Collection.collectionId='SMS00001'")
            Dim collectionRule As IResultObject = connection.CreateEmbeddedObjectInstance("SMS_CollectionRuleDirect")

            collectionRule("ResourceClassName").StringValue = "SMS_R_System"
            collectionRule("ResourceID").IntegerValue = outParams("ResourceID").IntegerValue

            Dim inParams2 As Dictionary(Of String, Object) = New Dictionary(Of String, Object)
            inParams2.Add("collectionRule", collectionRule)

            collection.ExecuteMethod("AddMembershipRule", inParams2)

            Return outParams("ResourceID").IntegerValue
        Catch e As SmsException
            Console.WriteLine("failed to add the computer" + e.Message)
            Throw
        End Try
    End Function

    Private Function Connect() As WqlConnectionManager
        Dim strSiteServer As String = ConfigurationManager.AppSettings("strSiteServer")
        Dim strSiteCode As String = ConfigurationManager.AppSettings("strSiteCode")
        Dim strUserName As String = ConfigurationManager.AppSettings("strUserName")
        Dim strPassword As String = ConfigurationManager.AppSettings("strPassword")

        Dim strHOSTNAME As String = System.Net.Dns.GetHostName().ToUpper()
        Dim strSCCMSERVER As String = strSiteServer.ToUpper()


        Try
            Dim namedValues As SmsNamedValuesDictionary = New SmsNamedValuesDictionary()
            Dim connection As WqlConnectionManager = New WqlConnectionManager(namedValues)

            If InStr(strSCCMSERVER, strHOSTNAME) Or InStr(strHOSTNAME, strSCCMSERVER) Then
                ' Connect to local computer.
                connection.Connect(strSiteServer)
            Else
                ' Connect to remote computer.
                connection.Connect(strSiteServer, strUserName, strPassword)
            End If

            Return connection
        Catch e As SmsException
            Console.WriteLine("Failed to Connect. Error: " + e.Message)
            Return Nothing
        Catch e As UnauthorizedAccessException
            Console.WriteLine("Failed to authenticate. Error:" + e.Message)
            Return Nothing
        End Try
    End Function

    Private Function AssociateComputer(ByVal referenceComputerResourceId As String, ByVal destinationComputerResourceId As String, ByVal connection As WqlConnectionManager) As String
        Dim iReturn As String = ""
        Try
            ' Set up the reference and destination computer in parameters.
            Dim inParams As Dictionary(Of String, Object) = New Dictionary(Of String, Object)
            inParams.Add("SourceClientResourceID", referenceComputerResourceId)
            inParams.Add("RestoreClientResourceID", destinationComputerResourceId)

            ' Create the computer association.
            Dim iResult As IResultObject = connection.ExecuteMethod("SMS_StateMigration", "AddAssociation", inParams)
            For Each oResult As IResultObject In iResult
                iReturn = "SUCCESS"
            Next
        Catch e As SmsException
            iReturn = "failed to make the association" + e.Message
            Throw
        End Try
        Return iReturn
    End Function

    Private Function GetResourceID(ByVal connection As WqlConnectionManager, ByVal ComputerName As String) As String
        Dim iResourceID As String = ""
        Try
            Dim query As IResultObject = connection.QueryProcessor.ExecuteQuery("SELECT ResourceID FROM SMS_R_System Where Name = '" & ComputerName & "'")
            Dim o As IResultObject
            For Each o In query
                iResourceID = o("ResourceID").StringValue
                o.Dispose()
            Next
        Catch ex As SmsException

        End Try
        Return iResourceID
    End Function

End Class






'